package com.mf.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.mf.config.GlobalParameter;
import com.mf.dto.MACD.MACDDto;
import com.mf.entity.Code;
import com.mf.entity.RecommendCode;
import com.mf.entity.code.*;
import com.mf.service.IHomeService;
import com.mf.service.ITapePurchaseHistoryService;
import com.mf.service.code.*;
import com.mf.service.impl.TapePurchaseHistoryServiceImpl;
import com.mf.utils.CCICalculator;
import com.mf.utils.CalculateKDJ;
import com.mf.utils.MACalculator;
import com.mf.utils.Result;
import com.mf.utils.calculate.KdjCalculator;
import com.mf.vo.MACD.MACDVo;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.apache.commons.beanutils.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author mf
 * @since 2024-04-30
 */
@RestController
@RequestMapping("/stock/code")
@Tag(name = "股票代码")
public class CodeController {

    @Resource
    private ICodeService codeService;

    @Resource
    TapePurchaseHistoryServiceImpl tapePurchaseHistoryService;

    @Resource
    private ICode600AService code600AService;

    @Resource
    private ICode600BService code600BService;

    @Resource
    private ICode000Service code000Service;

    @Resource
    private ICode001Service code001Service;

    @Resource
    private ICode002AService code002AService;

    @Resource
    private ICode002BService code002BService;

    @Resource
    private ICode003Service code003Service;
    @Resource
    private ICode300AService code300AService;
    @Resource
    private ICode300BService code300BService;
    @Resource
    private ICode301Service code301Service;
    @Resource
    private ICode601Service code601Service;
    @Resource
    private ICode603Service code603Service;
    @Resource
    private ICode605Service code605Service;
    @Resource
    private ICode688Service code688Service;
    @Resource
    private ICode689Service code689Service;

    @Resource
    private IHomeService homeService;
    @Operation(summary = "查询范围内对应k线")
    @GetMapping("/findHistoryK")
    public Result<MACDVo>  findHistoryK(@RequestParam("dm") String dm) throws InvocationTargetException, IllegalAccessException {
        System.out.println("查询");
        final LambdaQueryWrapper<RecommendCode> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(RecommendCode::getDm, dm);

        List<RecommendCode> list = new ArrayList<>();
        if (dm.startsWith("600")) {
            if (Integer.parseInt(dm) < 600500) {
                LambdaQueryWrapper<Code600A> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(Code600A::getDm, dm);
                final List<Code600A> list1 = code600AService.list(queryWrapper1);
                for (Code600A code : list1) {
                    final RecommendCode recommendCode = new RecommendCode();
                    BeanUtils.copyProperties(recommendCode, code);
                    list.add(recommendCode);
                }
            } else {
                LambdaQueryWrapper<Code600B> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(Code600B::getDm, dm);
                final List<Code600B> list1 = code600BService.list(queryWrapper1);
                for (Code600B code : list1) {
                    final RecommendCode recommendCode = new RecommendCode();
                    BeanUtils.copyProperties(recommendCode, code);
                    list.add(recommendCode);
                }
            }
        }else if(dm.startsWith("000")){
            LambdaQueryWrapper<Code000> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(Code000::getDm, dm);
            final List<Code000> list1 = code000Service.list(queryWrapper1);
            for (Code000 code : list1) {
                final RecommendCode recommendCode = new RecommendCode();
                BeanUtils.copyProperties(recommendCode, code);
                list.add(recommendCode);
            }
        }else if(dm.startsWith("001")){
            LambdaQueryWrapper<Code001> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(Code001::getDm, dm);
            final List<Code001> list1 = code001Service.list(queryWrapper1);
            for (Code001 code : list1) {
                final RecommendCode recommendCode = new RecommendCode();
                BeanUtils.copyProperties(recommendCode, code);
                list.add(recommendCode);
            }
        }else if(dm.startsWith("002")){
            if (Integer.parseInt(dm) < 2500) {
                LambdaQueryWrapper<Code002A> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(Code002A::getDm, dm);
                final List<Code002A> list1 = code002AService.list(queryWrapper1);
                for (Code002A code : list1) {
                    final RecommendCode recommendCode = new RecommendCode();
                    BeanUtils.copyProperties(recommendCode, code);
                    list.add(recommendCode);
                }
            } else  {
                LambdaQueryWrapper<Code002B> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(Code002B::getDm, dm);
                final List<Code002B> list1 = code002BService.list(queryWrapper1);
                for (Code002B code : list1) {
                    final RecommendCode recommendCode = new RecommendCode();
                    BeanUtils.copyProperties(recommendCode, code);
                    list.add(recommendCode);
                }
            }
        }else if(dm.startsWith("003")){
            LambdaQueryWrapper<Code003> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(Code003::getDm, dm);
            final List<Code003> list1 = code003Service.list(queryWrapper1);
            for (Code003 code : list1) {
                final RecommendCode recommendCode = new RecommendCode();
                BeanUtils.copyProperties(recommendCode, code);
                list.add(recommendCode);
            }
        }else if(dm.startsWith("300")){
            if (Integer.parseInt(dm) < 300500) {
                LambdaQueryWrapper<Code300A> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(Code300A::getDm, dm);
                final List<Code300A> list1 = code300AService.list(queryWrapper1);
                for (Code300A code : list1) {
                    final RecommendCode recommendCode = new RecommendCode();
                    BeanUtils.copyProperties(recommendCode, code);
                    list.add(recommendCode);
                }
            } else  {
                LambdaQueryWrapper<Code300B> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(Code300B::getDm, dm);
                final List<Code300B> list1 = code300BService.list(queryWrapper1);
                for (Code300B code : list1) {
                    final RecommendCode recommendCode = new RecommendCode();
                    BeanUtils.copyProperties(recommendCode, code);
                    list.add(recommendCode);
                }
            }
        }else if(dm.startsWith("301")){
            LambdaQueryWrapper<Code301> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(Code301::getDm, dm);
            final List<Code301> list1 = code301Service.list(queryWrapper1);
            for (Code301 code : list1) {
                final RecommendCode recommendCode = new RecommendCode();
                BeanUtils.copyProperties(recommendCode, code);
                list.add(recommendCode);
            }
        }else if(dm.startsWith("601")){
            LambdaQueryWrapper<Code601> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(Code601::getDm, dm);
            final List<Code601> list1 = code601Service.list(queryWrapper1);
            for (Code601 code : list1) {
                final RecommendCode recommendCode = new RecommendCode();
                BeanUtils.copyProperties(recommendCode, code);
                list.add(recommendCode);
            }
        }else if(dm.startsWith("603")){
            LambdaQueryWrapper<Code603> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(Code603::getDm, dm);
            final List<Code603> list1 = code603Service.list(queryWrapper1);
            for (Code603 code : list1) {
                final RecommendCode recommendCode = new RecommendCode();
                BeanUtils.copyProperties(recommendCode, code);
                list.add(recommendCode);
            }
        }else if(dm.startsWith("605")){
            LambdaQueryWrapper<Code605> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(Code605::getDm, dm);
            final List<Code605> list1 = code605Service.list(queryWrapper1);
            for (Code605 code : list1) {
                final RecommendCode recommendCode = new RecommendCode();
                BeanUtils.copyProperties(recommendCode, code);
                list.add(recommendCode);
            }
        }
        // 板块没有开通 查询没有意义
//        else if(dm.startsWith("688")){
//            LambdaQueryWrapper<Code688> queryWrapper1 = new LambdaQueryWrapper<>();
//            queryWrapper1.eq(Code688::getDm, dm);
//            final List<Code688> list1 = code688Service.list(queryWrapper1);
//            for (Code688 code : list1) {
//                final RecommendCode recommendCode = new RecommendCode();
//                BeanUtils.copyProperties(recommendCode, code);
//                list.add(recommendCode);
//            }
//        }else if(dm.startsWith("689")){
//            LambdaQueryWrapper<Code689> queryWrapper1 = new LambdaQueryWrapper<>();
//            queryWrapper1.eq(Code689::getDm, dm);
//            final List<Code689> list1 = code689Service.list(queryWrapper1);
//            for (Code689 code : list1) {
//                final RecommendCode recommendCode = new RecommendCode();
//                BeanUtils.copyProperties(recommendCode, code);
//                list.add(recommendCode);
//            }
//        }
        System.out.println(list.size());
        final MACDVo macdVo = setMacdVo(list);
        KdjCalculator.findIncreasingIndices2(macdVo);
        return Result.success(macdVo);
    }

    @GetMapping("/updateCode")
    @Operation(summary = "更新股票基本代码")
    public Result<Boolean> addCode() {
        codeService.remove(null);
        List<Code> listCode = codeService.getCode();
        return Result.success(codeService.saveBatch(listCode, 500));
    }

    public MACDVo setMacdVo(List<RecommendCode> codeList) {
        System.out.println(codeList);
        // 获取macd
        MACDVo macdVo =  homeService.findMacd(codeList);
        // 获取k线图
        double[][]  k =  homeService.getKLine(codeList);
        macdVo.setK(k);


        macdVo.setDm(codeList.get(0).getDm());

        final List<Double> ma5 = MACalculator.calculateMovingAverages(codeList, 5);
        final List<Double> ma10 = MACalculator.calculateMovingAverages(codeList, 10);
        final List<Double> ma20 = MACalculator.calculateMovingAverages(codeList, 20);
        final List<Double> ma30 = MACalculator.calculateMovingAverages(codeList, 30);
        macdVo.setMa5(ma5);
        macdVo.setMa10(ma10);
        macdVo.setMa20(ma20);
        macdVo.setMa30(ma30);

        // 设置kdj指标
        macdVo.setKdj(CalculateKDJ.getKDJ(macdVo));
        // 获取cci
        final List<Double> cciList = CCICalculator.calculateCCI(codeList, 14);
        macdVo.setCci(cciList);
        return  macdVo;
    }


    @Operation(summary = "新增当天最新数据")
    @GetMapping("/addNewestCode")
    public Result<Void> addNewestCode() {
        System.out.println("开始");
        List<Code000> code000s = codeService.addNewestCode000();
        System.out.println(code000s.size()+"数据");
        code000Service.saveBatch(code000s);
        System.out.println("code000添加成功");
        code001Service.saveBatch(codeService.addNewestCode001());
        System.out.println("code001添加成功");
        code002AService.saveBatch(codeService.addNewestCode002A());
        System.out.println("code002A添加成功");
        code002BService.saveBatch(codeService.addNewestCode002B());
        System.out.println("code002B添加成功");
        code003Service.saveBatch(codeService.addNewestCode003());
        System.out.println("code003添加成功");
        code300AService.saveBatch(codeService.addNewestCode300A());
        System.out.println("code300A添加成功");
        code300BService.saveBatch(codeService.addNewestCode300B());
        System.out.println("code300B添加成功");
        code301Service.saveBatch(codeService.addNewestCode301());
        System.out.println("code301添加成功");
        code600AService.saveBatch(codeService.addNewestCode600A());
        System.out.println("code600A添加成功");
        code600BService.saveBatch(codeService.addNewestCode600B());
        System.out.println("code600B添加成功");
        code601Service.saveBatch(codeService.addNewestCode601());
        System.out.println("code601添加成功");
        code603Service.saveBatch(codeService.addNewestCode603());
        System.out.println("code603添加成功");
        code605Service.saveBatch(codeService.addNewestCode605());
        System.out.println("code605添加成功");
//        板块没有开通暂时停止更新
//        code688Service.saveBatch(codeService.addNewestCode688());
//        System.out.println("code688添加成功");
//        code689Service.saveBatch(codeService.addNewestCode689());
//        System.out.println("code689添加成功");
        System.out.println("添加完成");
        System.out.println("开始计算可买入");
        tapePurchaseHistoryService.remove(null);
        tapePurchaseHistoryService.calculatedBuyIn();
        System.out.println("已完成所有步骤----->");

        return Result.success(null);
    }

    @GetMapping("findCode")
    @Operation(summary = "查询股票代码")
    public Result<List<Code>> findCode() {
        return Result.success(codeService.list());
    }

    public static <T> List<T> processAndSave(List<T> list) throws Exception {
        if (list == null || list.isEmpty()) {
            return null;
        }

        // 获取第一个元素的类
        Class<?> clazz = list.get(0).getClass();

        // 获取 getD 和 getDm 方法
        Method getDMethod = clazz.getMethod("getD");
        Method getDmMethod = clazz.getMethod("getDm");

        // 校验方法的可访问性，如果不是，则设置为可访问
        if (!getDMethod.isAccessible()) {
            getDMethod.setAccessible(true);
        }
        if (!getDmMethod.isAccessible()) {
            getDmMethod.setAccessible(true);
        }

        // 使用Stream API过滤列表，只保留具有唯一d和dm值的记录
        return new ArrayList<>(list.stream()
                .collect(Collectors.toMap(
                        item -> {
                            try {
                                // 组合d和dm的值作为Map的键
                                return Arrays.asList(
                                        getDMethod.invoke(item),
                                        getDmMethod.invoke(item)
                                );
                            } catch (Exception e) {
                                throw new RuntimeException("Error invoking getD or getDm method", e);
                            }
                        },
                        Function.identity(),
                        (existing, replacement) -> existing // 如果有冲突，保留现有的元素
                )).values());
    }
    @Operation(summary = "根据股票代码去重")
    @GetMapping("distinctCode")
    public Result<Void> distinctCode() throws Exception {
        // 000 去重
        List<Code000> code000List = code000Service.list();
        code000Service.remove(null);
        code000Service.saveBatch(processAndSave(code000List), 500);

        // 001 去重
        final List<Code001> code001List = code001Service.list();
        code001Service.remove(null);
        code001Service.saveBatch(processAndSave(code001List), 500);

        // 002A 去重
        final List<Code002A> code002AList = code002AService.list();
        code002AService.remove(null);
        code002AService.saveBatch(processAndSave(code002AList), 500);

        // 002B 去重
        final List<Code002B> code002BList = code002BService.list();
        code002BService.remove(null);
        code002BService.saveBatch(processAndSave(code002BList), 500);

        // 003 去重
        final List<Code003> code003List = code003Service.list();
        code003Service.remove(null);
        code003Service.saveBatch(processAndSave(code003List), 500);

        // 300A 去重
        final List<Code300A> code300AList = code300AService.list();
        code300AService.remove(null);
        code300AService.saveBatch(processAndSave(code300AList), 500);

        // 300B 去重
        final List<Code300B> code300BList = code300BService.list();
        code300BService.remove(null);
        code300BService.saveBatch(processAndSave(code300BList), 500);

        // 301 去重
        final List<Code301> code301List = code301Service.list();
        code301Service.remove(null);
        code301Service.saveBatch(processAndSave(code301List), 500);

        // 600A 去重
        final List<Code600A> code600AList = code600AService.list();
        code600AService.remove(null);
        code600AService.saveBatch(processAndSave(code600AList), 500);

        // 600B 去重
        final List<Code600B> code600BList = code600BService.list();
        code600BService.remove(null);
        code600BService.saveBatch(processAndSave(code600BList), 500);

        // 601 去重
        final List<Code601> code601List = code601Service.list();
        code601Service.remove(null);
        code601Service.saveBatch(processAndSave(code601List), 500);

        // 603 去重
        final List<Code603> code603List = code603Service.list();
        code603Service.remove(null);
        code603Service.saveBatch(processAndSave(code603List), 500);

        // 605 去重
        final List<Code605> code605List = code605Service.list();
        code605Service.remove(null);
        code605Service.saveBatch(processAndSave(code605List), 500);

        // 688去重
        final List<Code688> code688List = code688Service.list();
        code688Service.remove(null);
        code688Service.saveBatch(processAndSave(code688List), 500);

        // 689去重
        final List<Code689> code689List = code689Service.list();
        code689Service.remove(null);
        code689Service.saveBatch(processAndSave(code689List), 500);
        System.out.println("完成");
        return Result.success(null);
    }

    @Operation(summary = "补齐表中缺失数据")
    @GetMapping("repairMissingData")
    public Result<Void> repairMissingData() throws InvocationTargetException, IllegalAccessException {
        final LambdaQueryWrapper<Code> codeLambdaQueryWrapper = new LambdaQueryWrapper<>();
        codeLambdaQueryWrapper.notLike(Code::getMc, "ST");
        codeLambdaQueryWrapper.notLike(Code::getMc, "退");
        codeLambdaQueryWrapper.ne(Code::getStatus, 1);
        System.out.println("获取代码");
        List<Code> listAll = codeService.list(codeLambdaQueryWrapper);
        System.out.println("获取成功");

        String minCode000 = "000";
        String minCode001 = "001";
        String minCode002 = "002";
        String minCode003 = "003";
        String minCode300 = "300";
        String minCode301 = "301";
        String minCode600 = "600";
        String minCode601 = "601";
        String minCode603 = "603";
        String minCode605 = "605";
        String minCode688 = "688";
        String minCode689 = "689";


        List<Code> list000 = new ArrayList<>();
        List<Code> list001 = new ArrayList<>();
        List<Code> list002A = new ArrayList<>();
        List<Code> list002B = new ArrayList<>();
        List<Code> list003 = new ArrayList<>();
        List<Code> list300A = new ArrayList<>();
        List<Code> list300B = new ArrayList<>();
        List<Code> list301 = new ArrayList<>();
        List<Code> list600A = new ArrayList<>();
        List<Code> list600B = new ArrayList<>();
        List<Code> list601 = new ArrayList<>();
        List<Code> list603 = new ArrayList<>();
        List<Code> list605 = new ArrayList<>();
        List<Code> list688 = new ArrayList<>();
        List<Code> list689 = new ArrayList<>();
        for (Code code : listAll) {
            if (code.getDm().startsWith(minCode600)) {
                if (Integer.parseInt(code.getDm()) < 600500) {
                    list600A.add(code);
                } else  {
                    list600B.add(code);
                }
            }else if(code.getDm().startsWith(minCode000)){
                list000.add(code);
            }else if(code.getDm().startsWith(minCode001)){
                list001.add(code);
            }else if(code.getDm().startsWith(minCode002)){
                if (Integer.parseInt(code.getDm()) < 2500) {
                    list002A.add(code);
                } else  {
                    list002B.add(code);
                }
            }else if(code.getDm().startsWith(minCode003)){
                list003.add(code);
            }else if(code.getDm().startsWith(minCode300)){
                if (Integer.parseInt(code.getDm()) < 300500) {
                    list300A.add(code);
                } else  {
                    list300B.add(code);
                }
            }else if(code.getDm().startsWith(minCode301)){
                list301.add(code);
            }else if(code.getDm().startsWith(minCode601)){
                list601.add(code);
            }else if(code.getDm().startsWith(minCode603)){
                list603.add(code);
            }else if(code.getDm().startsWith(minCode605)){
                list605.add(code);
            }else if(code.getDm().startsWith(minCode688)){
                list688.add(code);
            }else if(code.getDm().startsWith(minCode689)){
                list689.add(code);
            }
        }




//        // 000 数据获取
//        List<Code000> listCode000_1 = code000Service.list();
//        // 查询没有添加的集合
//        Set<String> collect1 = listCode000_1.stream().map(Code000::getDm).collect(Collectors.toSet());
//        // 获取没有添加的集合
//        List<Code> collect000 = list000.stream().filter(code -> !collect1.contains(code.getDm())).toList();

        // 进行添加

//
//
//        // 001 数据获取
//        List<Code001> listCode001_1 = code001Service.list();
//        // 查询没有添加的集合
//        Set<String> collect2 = listCode001_1.stream().map(Code001::getDm).collect(Collectors.toSet());
//        // 获取没有添加的集合
//        List<Code> collect001 = list001.stream().filter(code -> !collect2.contains(code.getDm())).toList();
//
//
//        // 002A 数据获取
//        List<Code002A> listCode002A_1 = code002AService.list();
//        // 查询没有添加的集合
//        Set<String> collect3 = listCode002A_1.stream().map(Code002A::getDm).collect(Collectors.toSet());
//        // 获取没有添加的集合
//        List<Code> collect002A = list002A.stream().filter(code -> !collect3.contains(code.getDm())).toList();
//

        // 002B 数据获取
        List<Code002B> listCode002B_1 = code002BService.list();
        // 查询没有添加的集合
        Set<String> collect4 = listCode002B_1.stream().map(Code002B::getDm).collect(Collectors.toSet());
        // 获取没有添加的集合
        List<Code> collect002B = list002B.stream().filter(code -> !collect4.contains(code.getDm())).toList();


//        // 003 数据获取
//        List<Code003> listCode003_1 = code003Service.list();
//        // 查询没有添加的集合
//        Set<String> collect5 = listCode003_1.stream().map(Code003::getDm).collect(Collectors.toSet());
//        // 获取没有添加的集合
//        List<Code> collect003 = list003.stream().filter(code -> !collect5.contains(code.getDm())).toList();


//        // 300A 数据获取
//        List<Code300A> listCode300A_1 = code300AService.list();
//        // 查询没有添加的集合
//        Set<String> collect6 = listCode300A_1.stream().map(Code300A::getDm).collect(Collectors.toSet());
//        // 获取没有添加的集合
//        List<Code> collect300A = list300A.stream().filter(code -> !collect6.contains(code.getDm())).toList();
//
//
//        // 300B 数据获取
//        List<Code300B> listCode300B_1 = code300BService.list();
//        // 查询没有添加的集合
//        Set<String> collect7 = listCode300B_1.stream().map(Code300B::getDm).collect(Collectors.toSet());
//        // 获取没有添加的集合
//        List<Code> collect300B = list300B.stream().filter(code -> !collect7.contains(code.getDm())).toList();


//        // 301 数据获取
//        List<Code301> listCode301_1 = code301Service.list();
//        // 查询没有添加的集合
//        Set<String> collect8 = listCode301_1.stream().map(Code301::getDm).collect(Collectors.toSet());
//        // 获取没有添加的集合
//        List<Code> collect301 = list301.stream().filter(code -> !collect8.contains(code.getDm())).toList();

//
//        // 601 数据获取
//        List<Code601> listCode601_1 = code601Service.list();
//        // 查询没有添加的集合
//        Set<String> collect9 = listCode601_1.stream().map(Code601::getDm).collect(Collectors.toSet());
//        // 获取没有添加的集合
//        List<Code> collect601 = list601.stream().filter(code -> !collect9.contains(code.getDm())).toList();


//        // 603 数据获取
//        List<Code603> listCode603_1 = code603Service.list();
//        // 查询没有添加的集合
//        Set<String> collect10 = listCode603_1.stream().map(Code603::getDm).collect(Collectors.toSet());
//        // 获取没有添加的集合
//        List<Code> collect603 = list603.stream().filter(code -> !collect10.contains(code.getDm())).toList();

//
//        // 605 数据获取
//        List<Code605> listCode605_1 = code605Service.list();
//        // 查询没有添加的集合
//        Set<String> collect11 = listCode605_1.stream().map(Code605::getDm).collect(Collectors.toSet());
//        // 获取没有添加的集合
//        List<Code> collect605 = list605.stream().filter(code -> !collect11.contains(code.getDm())).toList();

//
//        // 688 数据获取
//        List<Code688> listCode688_1 = code688Service.list();
//        // 查询没有添加的集合
//        Set<String> collect12 = listCode688_1.stream().map(Code688::getDm).collect(Collectors.toSet());
//        List<Code> collect688 = list688.stream().filter(code -> !collect12.contains(code.getDm())).toList();


//        // 689 数据获取
//        List<Code689> listCode689_1 = code689Service.list();
//        // 查询没有添加的集合
//        Set<String> collect13 = listCode689_1.stream().map(Code689::getDm).collect(Collectors.toSet());
//        List<Code> collect689 = list689.stream().filter(code -> !collect13.contains(code.getDm())).toList();
//
//
//        // 600A 数据获取
//        List<Code600A> listCode600A_1 = code600AService.list();
//        // 查询没有添加的集合
//        Set<String> collect14 = listCode600A_1.stream().map(Code600A::getDm).collect(Collectors.toSet());
//        List<Code> collect600A = list600A.stream().filter(code -> !collect14.contains(code.getDm())).toList();
//
//
//        // 600B 数据获取
//        List<Code600B> listCode600B_1 = code600BService.list();
//        // 查询没有添加的集合
//        Set<String> collect15 = listCode600B_1.stream().map(Code600B::getDm).collect(Collectors.toSet());
//        List<Code> collect600B = list600B.stream().filter(code -> !collect15.contains(code.getDm())).toList();



// 查询不完整数据
//        Map<String, List<Code000>> collect = list1.stream().collect(Collectors.groupingBy(Code000::getDm));
//        collect.forEach((dm, code000s) -> {
//            if(code000s.size() != 27){
//                System.out.println(dm);
//                System.out.println(code000s.size());
//                System.out.println("============");
//            }
//        });


//        findCodeHistoryList(collect600B, Code600B.class);
//        findCodeHistoryList(collect600A, Code600A.class);
//        findCodeHistoryList(collect689, Code689.class);
//        findCodeHistoryList(collect688, Code688.class);
//        findCodeHistoryList(collect605, Code605.class);
//        findCodeHistoryList(collect603, Code603.class);
//        findCodeHistoryList(collect601, Code601.class);
//        findCodeHistoryList(collect301, Code301.class);
        System.out.println(collect002B.size()+"=========");
        int count = collect002B.size();
        for (Code code : collect002B) {
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            final MACDDto macdDto = new MACDDto();
            macdDto.setDm(code.getDm());
            macdDto.setType("dn");
            final List<RecommendCode> historicalData = codeService.findHistoricalData(macdDto);

            // 获取当前日期
            LocalDate now = LocalDate.now();
            // 计算一个半月前的日期
            LocalDate oneAndHalfMonthAgo = now.minusMonths(1).minusDays(15);
            // 获取前一个半月的数据
            List<RecommendCode> filteredData = historicalData.stream()
                    .filter(recommendCode -> {
                        LocalDate date = LocalDate.parse(recommendCode.getD(), GlobalParameter.FORMATTER2);
                        return !date.isBefore(oneAndHalfMonthAgo);
                    })
                    .toList();
            List<Code002B> list = new ArrayList<>();
            for (RecommendCode code2 : filteredData) {
                code2.setId(null);
                final Code002B code301 = new Code002B();
                BeanUtils.copyProperties(code301, code2);
                list.add(code301);
            }
            System.out.println("?????"+code.getDm());

            if(list.isEmpty()){
                System.out.println("====");
                UpdateWrapper<Code> codeUpdateWrapper = new UpdateWrapper<>();
                codeUpdateWrapper.eq("dm",code.getDm());
                codeUpdateWrapper.set("status", 1);
                codeService.update(codeUpdateWrapper);
            }else{
                code002BService.saveBatch(list, 500);
            }
            count--;
            System.out.println(count);
        }
        System.out.println("12313132");
//        findCodeHistoryList(collect300B, Code300B.class);
//        findCodeHistoryList(collect300A, Code300A.class);

//
//
//
//        System.out.println("开始获取外部接口");

//        findCodeHistoryList(collect003, Code003.class);
//        findCodeHistoryList(collect002B, Code002B.class);
//        findCodeHistoryList(collect002A, Code002A.class);
//        findCodeHistoryList(collect001, Code001.class);
//        findCodeHistoryList(collect000, Code000.class);
        return Result.success(null);
    }

    /**
     * 查询对应股票代码历史数据
     */
    public <T> void findCodeHistoryList(List<Code> codeList, Class<T> codeClass) {
        if(codeList.isEmpty()){
            System.out.println("已经没有数据可添加了");
            return;
        }
        //删除表中以前的所有推荐
        // 获取当前日期
        LocalDate now = LocalDate.now();
        // 计算一个半月前的日期
        LocalDate oneAndHalfMonthAgo = now.minusMonths(1).minusDays(15);


        // 使用固定大小的线程池
        ExecutorService executor = Executors.newFixedThreadPool(4);
//        CountDownLatch latch = new CountDownLatch(codeList.size()); // 使用CountDownLatch等待所有任务完成
        //  提交任务到线程池
        for (final Code code : codeList) {
            executor.submit(new Callable<Boolean>() {
                @Override
                public Boolean call() throws Exception {
                    final MACDDto macdDto = new MACDDto();
                    macdDto.setDm(code.getDm());
                    macdDto.setType("dn");
                    final List<RecommendCode> historicalData = codeService.findHistoricalData(macdDto);

                    // 获取前一个半月的数据
                    List<RecommendCode> filteredData = historicalData.stream()
                            .filter(recommendCode -> {
                                LocalDate date = LocalDate.parse(recommendCode.getD(), GlobalParameter.FORMATTER2);
                                return !date.isBefore(oneAndHalfMonthAgo);
                            })
                            .toList();


                    List<T> list = new ArrayList<>();
                    for (RecommendCode code : filteredData) {
                        code.setId(null);
                        T codeInstance = codeClass.getDeclaredConstructor().newInstance();
                        BeanUtils.copyProperties(codeInstance, code);
                        list.add(codeInstance);
                    }
                    System.out.println(historicalData.size());
                    if (codeClass.getDeclaredConstructor().newInstance() instanceof Code600A) {
                        // 强制类型转换，因为我们已经检查了instanceof
                        code600AService.saveBatch((Collection<Code600A>) list, 500);
                    }else if(codeClass.getDeclaredConstructor().newInstance() instanceof Code600B){
                        code600BService.saveBatch((Collection<Code600B>) list, 500);
                    }else if(codeClass.getDeclaredConstructor().newInstance() instanceof Code000){
                        code000Service.saveBatch((Collection<Code000>) list, 500);
                    }else if(codeClass.getDeclaredConstructor().newInstance() instanceof Code001){
                        code001Service.saveBatch((Collection<Code001>) list, 500);
                    }else if(codeClass.getDeclaredConstructor().newInstance() instanceof Code002A){
                        code002AService.saveBatch((Collection<Code002A>) list, 500);
                    }else if(codeClass.getDeclaredConstructor().newInstance() instanceof Code002B){
                        code002BService.saveBatch((Collection<Code002B>) list, 500);
                    }else if(codeClass.getDeclaredConstructor().newInstance() instanceof Code003){
                        code003Service.saveBatch((Collection<Code003>) list, 500);
                    }else if(codeClass.getDeclaredConstructor().newInstance() instanceof Code300A){
                        code300AService.saveBatch((Collection<Code300A>) list, 500);
                    }else if(codeClass.getDeclaredConstructor().newInstance() instanceof Code300B){
                        code300BService.saveBatch((Collection<Code300B>) list, 500);
                    }else if(codeClass.getDeclaredConstructor().newInstance() instanceof Code301){
                        code301Service.saveBatch((Collection<Code301>) list, 500);
                    }else if(codeClass.getDeclaredConstructor().newInstance() instanceof Code601){
                        code601Service.saveBatch((Collection<Code601>) list, 500);
                    }else if(codeClass.getDeclaredConstructor().newInstance() instanceof Code603){
                        code603Service.saveBatch((Collection<Code603>) list,500);
                    }else if(codeClass.getDeclaredConstructor().newInstance() instanceof Code605){
                        code605Service.saveBatch((Collection<Code605>) list, 500);
                    }else if(codeClass.getDeclaredConstructor().newInstance() instanceof Code688){
                        code688Service.saveBatch((Collection<Code688>) list, 500);
                    }else if(codeClass.getDeclaredConstructor().newInstance() instanceof Code689){
                        code689Service.saveBatch((Collection<Code689>) list,500);
                    }
                    // 并且 cci大于前一日的
//                    latch.countDown(); // 任务完成，计数减一

                    if(list.isEmpty()){
                        UpdateWrapper<Code> codeUpdateWrapper = new UpdateWrapper<>();
                        codeUpdateWrapper.eq("dm",code.getDm());
                        codeUpdateWrapper.set("status", 1);
                        codeService.update(codeUpdateWrapper);
                    }


                    System.out.println(list.size()+"=========latch======");
                    System.out.println(code.getDm());
                    return null;
                }
            });
        }
        // 等待所有任务完成
//            latch.await();
            System.out.println("????");;
            // 关闭线程池
//            executor.shutdown();



    }

}
